package ca.cbc.msb.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpServiceUtil 
{
	private static Logger logger = LoggerFactory.getLogger(HttpServiceUtil.class);


	private static int CONNECTION_TIMEOUT =  1000 * 90;
	
	/**
	 * This methods takes some parameters and visit the URL to get response
	 * @param urlStr -- URL string to visit
	 * @param postParamStr -- parameter past using POST method
	 * @return response string	 
	 * @throws IOException 
	 * */
	public static String postText(String urlStr, String postParamStr) throws IOException
	{
		String responseStr = "";
		BufferedReader in = null;
		OutputStreamWriter out = null;
	
		//logger.debug("^^^URL visiting is {}, POST parameter is {}", urlStr, postParamStr);
		int listenTimeout = Integer.valueOf(AppConfig.getProperty("theplatform.notification.timeout"));
		try 
		{		
			URL feedURL = new URL(urlStr.toString());
			URLConnection rc = feedURL.openConnection();

			rc.setReadTimeout(listenTimeout);
			rc.setConnectTimeout(CONNECTION_TIMEOUT);
			
			//use POST method to pass token for security
			if(postParamStr != null && !postParamStr.trim().equals(""))
			{
				rc.setDoOutput(true);
				out = new OutputStreamWriter(rc.getOutputStream());
				out.write(postParamStr);
				out.flush();
			}
			
			//read the response
			in = new BufferedReader(new InputStreamReader(rc.getInputStream()));
			
			String tmpStr;
			while ((tmpStr = in.readLine()) != null) {
				responseStr += tmpStr;
			}
	        
		} catch (SocketTimeoutException e){
			logger.error("Listen URL {} timed out in {} seconds", urlStr, listenTimeout/1000.0);
		}
		finally
		{
			if(in != null)
				in.close();

			if(out != null)
				out.close();	
		}
		
		//logger.debug("^^^URL Response is {}", responseStr);
		
        return responseStr;
	}

}
